import { IMiddleware, Inject, Middleware, MidwayWebRouterService, RouterInfo } from "@midwayjs/core";
import { Context, NextFunction } from "@midwayjs/koa";
import { RedisService } from '@midwayjs/redis'
import { BaseError as R } from '../common/base.error'


@Middleware()
export class AuthMiddleware implements IMiddleware<Context, NextFunction> {

  @Inject()
  redisService: RedisService

  @Inject()
  webRouterService: MidwayWebRouterService

  @Inject()
  notLoginRouters: RouterInfo[]

  resolve() {
    return async (ctx: Context, next: NextFunction) => {

      const routeInfo = await this.webRouterService.getMatchedRouterInfo(
        ctx.path,
        ctx.method
      );
      // console.log(11111111111, this.webRouterService, routeInfo)

      if (!routeInfo) {
        await next();
        return;
      }

      if (
        this.notLoginRouters.some(
          o =>
            o.requestMethod === routeInfo.requestMethod &&
            o.url === routeInfo.url
        )
      ) {
        await next();
        return;
      }

      if (!ctx.headers.authorization) {
        throw R.unauthrizedError('未授权!')
      }
      
      // const token = ctx.headers.authorization.replace('Bearer ', '');
      // if (!token) {
      //   throw R.unauthrizedError('未授权!')
      // }

      // const userinfoStr = await this.redisService.get(`token:${token}`);
      // console.log('授权：', userinfoStr, token);
      // if (!userinfoStr) {
      //   throw R.unauthrizedError('未授权!')
      // }

      // const userinfo = JSON.parse(userinfoStr);
      // ctx.userinfo = userinfo;
      ctx.token = ctx.headers.authorization;

      return next()
    }   
  }

  static getName() {
    return 'auth'
  }
}